Browser Compatibility: NS, IE, others
|
Do you remember the old hover button script we worked on a while back? Then you probably remember how much trouble it was to detect the browser type before we could run the script. Here was how we had to do it:
browserName=navigator.appName;
browserVer=parseInt(navigator.appVersion);
if ((browserName=="Netscape" && browserVer>=3) || (browserName=="Microsoft Internet Explorer" && browserVer>=4))
version="n3";
else
version="n2";
That is a lot of code to run through, and it can be much worse when you create a script that has alot of browser differences. Well, instead of checking for the browser, we could have checked for the javascript object that we needed for the script to work. Since we know that the hover button script needed the document.images object to work, we could have shortened the above code to say:
if (document.images)
{ ...code...}
In fact, this object just so happens to exist in the browsers we checked for, and not in the browsers that were excluded. So, using this object detection code, we are checking for Netscape 3 or higher, and MS Internet Explorer 4 or higher! And as a bonus, if any other browser happens to recognize the document.images object, the script will run for them too! (Opera perhaps?)
You can also use a couple of the new objects to check for version 4 browsers. If you are looking only for NS4 or better, check for the document.layers object:
if (document.layers)
{ ...code...}
If you want only IE4 or better, check for the document.all object. (May change when NS5 arrives):
if (document.all)
{ ...code...}
Of course, if you just want it to work for either version 4 browser, check to see if the browser has one object or the other:
if (document.all || document.layers)
{ ...code...}
You can find some more uses for this as you are coding, so that you can avoid those pesky javascript errors in older browsers. While you are at it, it will probably keep away those errors with the newer browsers as well.
Well, that does it for now, try out the next section on More JavaScript Buttons.
The tutorials and articles on these pages are © 1997-99 by John Pollock and may not be reposted without written permission from the author, and may not be reprinted for profit. |
|
![]() |
Email: [email protected] |
![]() |